import store from '@/store';
import Vue from 'vue';
import VueRouter from 'vue-router';
import routes from './routes';

Vue.use(VueRouter);

// 解决编程时导航报错问题
const OriginPush = VueRouter.prototype.push;
const OriginReplace = VueRouter.prototype.replace;
VueRouter.prototype.push = function (path, okCallBack, errCallBack) {
  if (okCallBack === undefined && errCallBack === undefined) {
    OriginPush.call(this, path).catch(() => {});
  } else {
    OriginPush.call(this, path, okCallBack, errCallBack);
  }
};
VueRouter.prototype.replace = function (path, okCallBack, errCallBack) {
  if (okCallBack === undefined && errCallBack === undefined) {
    OriginReplace.call(this, path).catch(() => {});
  } else {
    OriginReplace.call(this, path, okCallBack, errCallBack);
  }
};

const router = new VueRouter({
  routes,
  mode: 'history',
  scrollBehavior(to, from, savedPosition) {
    // return 期望滚动到哪个的位置
    if (savedPosition) {
      return savedPosition;
    } else {
      return { x: 0, y: 0 };
    }
  }
});

// 路由守卫
// 白名单,这些不需要登录可以访问
const whiteList = ['home', 'login', 'register', 'search', 'detail', 'addcartsuccess', 'shopcart'];
router.beforeEach((to, from, next) => {
  // 放行的条件:
  // 1. 需要放行的页面，我们才给放行  login register home detail search shopcart
  // 2. 某些需要登陆才能查看的页面，如果有token的话 也可以放行
  // 3. 其余的情况必须先登陆 可以让其先跳转到登陆页面
  if (whiteList.includes(to.name) || store.state.user.user.token) {
    next();
    return; // 禁止下边继续执行
  }
  next({
    name: 'login',
    query: {
      redirect: to.path
    }
  });
});

export default router;
